package com.zcg.blogger.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zcg.blogger.exception.UserException;
import com.zcg.blogger.model.Message;
import com.zcg.blogger.service.MessageService;

@Controller
@RequestMapping("/message")
public class MessageController {
	
	@Resource
	private MessageService messageService;
	
	/**
	 * 增加留言页面
	 * @param message
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(@ModelAttribute Message message,Model model){
		return "/message/add";
	}
	
	/**
	 * 增加留言
	 * @param message
	 * @param br
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/list","/add","/"},method=RequestMethod.POST)
	public String add(@Validated Message message, BindingResult br, Model model){
		if(message.getUser().getId() == 0){
			throw new UserException("请先登录");
		}
		if (br.hasErrors()) {
			return "message/add";
		}
		messageService.add(message);
		model.addAttribute(message);
		return "redirect:./";
	}
	
	/**
	 * 留言列表
	 * @param message
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value={"/list","/"},method=RequestMethod.GET)
	private String list(@ModelAttribute Message message,Model model, HttpSession session) {
		List<Message> messages = messageService.loadMessageAll();
		int messageCount = messageService.countAll();
		model.addAttribute("messages", messages);
		model.addAttribute("messageCount",messageCount);
		model.addAttribute("url", "message/");
		return "message/index";
	}
}
